import ElementPlus from 'unplugin-element-plus/vite';
import { webUpdateNotice } from '@plugin-web-update-notification/vite';
import legacy from '@vitejs/plugin-legacy';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import autoprefixer from 'autoprefixer';
import { codeInspectorPlugin } from 'code-inspector-plugin';
import fs from 'fs';
import path from 'path';
import postCssPxToRem from 'postcss-pxtorem';
import copy from 'rollup-plugin-copy';
import { visualizer } from 'rollup-plugin-visualizer';
import UnoCSS from 'unocss/vite';
import Printer from 'unplugin-printer/vite';
import TurboConsole from 'unplugin-turbo-console/vite';
import { defineConfig } from 'vite';
import cesium from 'vite-plugin-cesium';
import viteCompression from 'vite-plugin-compression';
import vitePluginNoBug from 'vite-plugin-no-bug';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';

// https://vitejs.dev/config/
export default defineConfig(() => {
  // 这里只加入了element的有其他的也加在这里
  const optimizeDepsElementPlusIncludes = ['element-plus/es'];

  //  预加载element样式 有其他组件也是如此设置即可
  fs.readdirSync('node_modules/element-plus/es/components').forEach((dirname) => {
    fs.access(
      // 其他框架这个路径根据控制台输出进行修改 有的项目时加载的是 css.mjs 有些是 index.mjs 这个路径vite控制台能够看出来
      `node_modules/element-plus/es/components/${dirname}/style/index.mjs`,
      (err) => {
        if (!err) {
          optimizeDepsElementPlusIncludes.push(`element-plus/es/components/${dirname}/style/index`);
        }
      },
    );
  });

  return {
    base: './',
    plugins: [
      vue(),
      cesium({ rebuildCesium: true }),

      vueJsx(),
      copy({
        targets: [
          { src: 'node_modules/@liveqing/liveplayer-v3/dist/component/liveplayer-lib.min.js', dest: 'public/js' },
        ],
      }),
      viteCompression({
        algorithm: 'gzip',
        verbose: false,
        filter: /\.(js)$/,
        deleteOriginFile: false, // 删除源文件
      }),

      legacy({
        targets: ['defaults', 'not IE 11'],
      }),
      UnoCSS({
        configFile: './unocss.config.js',
      }),
      vitePluginNoBug(),
      ElementPlus({
        useSource: true,
        ignoreComponents: ['AutoResizer'],
      }),
      visualizer({ gzipSize: true }),
      TurboConsole({
        prefix: '___________打印 ↓_____________',
        suffix: '___________打印 ↑_____________',
      }),
      Printer({
        info: [
          ({ lightCyan, green, bold }) => {
            return `  ${green('➜')}  ${bold('官网')}:  ${lightCyan('https://whyfail.gitee.io/cwa-document/')}`;
          },
        ],
      }),
      codeInspectorPlugin({
        bundler: 'vite',
      }),
      webUpdateNotice({
        notificationProps: {
          title: '系统升级通知',
          description: '检测到当前系统版本已更新，请刷新页面后使用',
          buttonText: '刷新',
          dismissButtonText: '忽略',
        },
      }),

      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/assets/svg-icons')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
    resolve: {
      alias: {
        '@': '/src',
      },
    },
    assetsInclude: ['**/*.mp3', '**/*.MP3'],
    css: {
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue: 16, // 1rem的大小
            propList: ['*'], // 需要转换的属性，这里选择全部都进行转换
            selectorBlackList: ['#app'],
          }),
          autoprefixer({
            grid: true,
            overrideBrowserslist: ['> 1%'],
          }),
        ],
      },
      preprocessorOptions: {
        scss: {
          // 自定义的主题色
          additionalData: `@use "@/assets/css/element-plus.scss" as *;`,
        },
      },
    },
    server: {
      host: true,
      open: true,
      proxy: {
        // 代理
        '/hls_base': {
          // target: 'http://192.168.200.49:7081', // 仁浩本地
          target: 'https://123.178.187.98:7080/hls_base',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/hls_base/, ''),
        },
        '/hls-specimen': {
          // target: 'http://192.168.200.193:13456', // 徐涛本地
          // target: 'http://192.168.200.49:3457', // 仁浩本地
          target: 'https://123.178.187.98:7080/hls-specimen',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/hls-specimen/, ''),
        },
        '/geoserver': {
          target: 'http://192.168.200.49:8081/geoserver',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/geoserver/, ''),
        },

        '/nnewtiles': {
          target: 'http://192.168.2.201',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/nnewtiles/, ''),
        },

        '/tianditu_api': {
          target: 'https://api.tianditu.gov.cn',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/tianditu_api/, ''),
        },
        '/st_server_api': {
          target: 'http://192.168.2.20:9191',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/st_server_api/, '/st_server_api'),
        },
        '/st_server_api_v2': {
          target: 'https://www.xazrhh.com:1443/st_server_api',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/st_server_api_v2/, ''),
        },
      },
      watch: {
        // 忽略大文件或不需要热更新的目录
        ignored: ['**/*.mp4'],
      },
    },
    optimizeDeps: {
      include: optimizeDepsElementPlusIncludes,
    },
    esbuild: {
      // drop: ['debugger', 'console'],
    },
    build: {
      // 清除console和debugger
      terserOptions: {
        // compress: {
        //   drop_console: false,
        //   drop_debugger: true,
        // },
      },
      rollupOptions: {
        output: {
          //配置这个是让不同类型文件放在不同文件夹，不会显得太乱
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: '[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            //静态资源分拆打包
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
        },
      },
      target: 'modules',
      outDir: 'dist', // 指定输出路径
      assetsDir: 'assets', // 指定生成静态文件目录
      assetsInlineLimit: '4096', // 小于此阈值的导入或引用资源将内联为 base64 编码
      minify: 'terser', // 混淆器，terser构建后文件体积更小
      emptyOutDir: true, //打包前先清空原有打包文件
      chunkSizeWarningLimit: 1500,
      reportCompressedSize: false,
    },
  };
});
